import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:im_module/common/GroupCommonType.dart';
import 'package:im_module/manager/ImChatManager.dart';
import 'package:im_module/message/ImChatWidget.dart';
import 'package:im_module/model/UserMember.dart';
import 'package:im_module/provider/im_provider.dart';
import 'package:im_module/widget/AppBarBackground.dart';
import 'package:im_module/widget/ImHeadImageWidget.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';

// ignore: must_be_immutable
class ChooseContactWidget extends StatefulWidget {
  String? groupId;
  List<String>? groupNumber;

  ChooseContactWidget({String? groupId, List<String>? groupNumber}) {
    this.groupId = groupId;
    this.groupNumber = groupNumber;
  }

  @override
  _ChooseContactWidgetState createState() => _ChooseContactWidgetState();
}

class _ChooseContactWidgetState extends State<ChooseContactWidget> {
  //已经选择的用户
  Map<String, V2TimUserFullInfo?> _mSelectUserMap = new Map();

  @override
  void initState() {
    super.initState();
    //获取好友
    ImChatManager().getFriendList();

    print("以选择的好友:${widget.groupNumber.toString()}");
  }

  ///创建群聊
  void createGroup() async {
    if (_mSelectUserMap.isEmpty) {
      return;
    }
    List<Map> memberList = List.empty(growable: true);
    String groupName = '群:';

    int i = 0;
    _mSelectUserMap.forEach((key, value) {
      Map user = new Map();
      user['userID'] = key;
      user['role'] = GroupCommonType.V2TIM_GROUP_MEMBER_ROLE_MEMBER;
      memberList.add(user);
      groupName += "${value?.nickName}";
      i++;
      if (i != _mSelectUserMap.length) {
        groupName += ",";
      }
    });
    if (groupName.length > 10) {
      groupName = groupName.substring(0, 10) + '...';
    }
    //创建群聊
    ImChatManager().createGroup(groupName, memberList).then(
          (String? groupId) => {
            if (groupId != null)
              {
                Navigator.pushReplacement(context,
                    MaterialPageRoute(builder: (_) {
                  return new ImChatWidget(
                    type: 2,
                    id: groupId,
                    niceName: groupName, //对方好友备注->对方昵称->对方的 userID
                  );
                })),
                /*ImChatManager().insertGroupMessageToLocalStorage(
                    "创建了群聊", ImChatManager().getUserId(), groupId),*/
              },
          },
        );
  }

  ///邀请人员加群
  void inviteUserToGroup(String groupID) async {
    if (_mSelectUserMap.isEmpty) {
      return;
    }
    List<String> ids = List.empty(growable: true);
    _mSelectUserMap.keys.forEach((element) {
      ids.add(element);
    });

    /*bool flag =  await ImChatManager().inviteUserToGroup(groupID, ids);
    if(flag){
      _mSelectUserMap.clear();
    }*/
    ImChatManager().inviteUserToGroup(groupID, ids).then((value) {
      if (value) {
        Navigator.pop(context, true);
      } else {
        Navigator.pop(context, false);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return AppBarBackground(
      child: Scaffold(
        appBar: AppBar(
          title: Text("选择联系人"),
          actions: [
            TextButton(
              onPressed: () {
                //如果群id为空，则表示为创建群
                if (widget.groupId == null) {
                  createGroup();
                } else {
                  inviteUserToGroup(widget.groupId!);
                }
              },
              child: Text(
                "完成",
                style: TextStyle(color: Colors.white),
              ),
            )
          ],
        ),
        body: Container(
          color: Colors.white,
          child: Column(
            children: [
              SizedBox(
                height: 15,
              ),
              Expanded(child: Consumer<ImProvider>(
                builder: (context, _provider, _) {
                  if (_provider.friendList.isEmpty) {
                    return Center(
                      child: Text("暂无好友"),
                    );
                  } else {
                    /*return ListView.separated(
                      itemBuilder: (context, index) {
                        V2TimFriendInfo application =
                            _provider.friendList[index];

                        return CheckboxListTile(
                          secondary: ImHeadImageWidget(
                              "${application.userProfile?.faceUrl}"),
                          value:
                              _mSelectUserMap.containsKey(application.userID),
                          onChanged:
                              widget.groupNumber!.contains(application.userID)
                                  ? null
                                  : (bool? value) {
                                      setState(() {
                                        if (value!) {
                                          _mSelectUserMap[application.userID] =
                                              application.userProfile;
                                        } else {
                                          _mSelectUserMap
                                              .remove(application.userID);
                                        }
                                      });
                                    },
                          title: Text("${application.userProfile?.nickName}"),
                        );
                      },
                      separatorBuilder: (context, index) => Divider(
                        height: .5,
                      ),
                      itemCount: _provider.friendList.length,
                    );*/

                    List<V2TimFriendInfo> _data = _provider.friendList;
                    List<UserMember> _list = List.empty(growable: true);
                    for (var value in _data) {
                      UserMember _userMember = UserMember(userId: value.userID);

                      _userMember.userProfile = value.userProfile;
                      _userMember.avatar = "${value.userProfile?.faceUrl}";
                      String nickName = "${value.userProfile?.nickName}";
                      _userMember.nickName = nickName;

                      String pinyin = PinyinHelper.getPinyinE(nickName);
                      String tag = pinyin.substring(0, 1).toUpperCase();
                      _userMember.namePinyin = pinyin;

                      if (RegExp("[A-Z]").hasMatch(tag)) {
                        _userMember.tagIndex = tag;
                      } else {
                        _userMember.tagIndex = "#";
                      }
                      _list.add(_userMember);
                    }

                    // A-Z sort.
                    SuspensionUtil.sortListBySuspensionTag(_list);

                    // show sus tag.
                    SuspensionUtil.setShowSuspensionStatus(_list);

                    return AzListView(
                      data: _list,
                      itemCount: _list.length,
                      itemBuilder: (BuildContext context, int index) {
                        UserMember model = _list[index];
                        return _buildListItem(context, model);
                      },
                      //physics: BouncingScrollPhysics(),
                      //physics: new NeverScrollableScrollPhysics(),
                      indexBarData: SuspensionUtil.getTagIndexList(_list),
                    );
                  }
                },
              )),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildListItem(context, UserMember model) {
    String susTag = model.getSuspensionTag();
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15.0),
      child: Column(
        children: <Widget>[
          Offstage(
            offstage: model.isShowSuspension != true,
            child: _buildSusWidget(susTag),
          ),
          CheckboxListTile(
            secondary: ImHeadImageWidget("${model.avatar}"),
            value: _mSelectUserMap.containsKey(model.userId),
            onChanged: widget.groupNumber!.contains(model.userId)
                ? null
                : (bool? value) {
                    setState(() {
                      if (value!) {
                        _mSelectUserMap[model.userId] = model.userProfile;
                      } else {
                        _mSelectUserMap.remove(model.userId);
                      }
                    });
                  },
            title: Text("${model.nickName}"),
          )
        ],
      ),
    );
  }

  Widget _buildSusWidget(String susTag) {
    return Container(
      height: 30,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      child: Row(
        children: <Widget>[
          Text(
            '$susTag',
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
          Expanded(
              child: Divider(
            height: .0,
            indent: 10.0,
          ))
        ],
      ),
    );
  }
}
